import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:cached_network_image/cached_network_image.dart';

class TeamPage extends StatefulWidget {
  TeamPage({Key key}) : super(key: key);

  @override
  _TeamPageState createState() => _TeamPageState();
}

class _TeamPageState extends State<TeamPage> {
  String phone = '';
  String nickname = '';
  String register_time = '';
  String avatar = '';
  int page = 1;
  String token = "";
  EasyRefreshController _controller = new EasyRefreshController();
  int groupValue = 0;
  List listData = new List();
  List cates = [
    {'cat_id': '0', 'cat_name': '普通会员'},
    {'cat_id': '1', 'cat_name': '产品礼包1'},
    {'cat_id': '2', 'cat_name': '产品礼包2'},
    {'cat_id': '3', 'cat_name': '产品礼包3'}
  ];

  String group_id = '2';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '产品业绩',
          style: TextStyle(
              color: black,
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
        ),
        backgroundColor: white,
        brightness: Brightness.light,
        elevation: 0.2,
        iconTheme: IconThemeData(color: black_99),
      ),
      body: new EasyRefresh(
          enableControlFinishRefresh: true,
          enableControlFinishLoad: true,
          header: MaterialHeader(),
          footer: MaterialFooter(),
          controller: _controller,
          child: CustomScrollView(slivers: <Widget>[
            SliverToBoxAdapter(
                child: Container(
              color: white,
              alignment: Alignment.centerLeft,
              child: Column(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.all(8),
                    alignment: Alignment.centerLeft,
                    child: Text('推荐人',
                        style: TextStyle(
                            color: Colors.orange,
                            fontSize: ScreenUtil.getInstance().setSp(30))),
                  ),
                  Row(
                    children: <Widget>[
                      Container(
                          margin: EdgeInsets.all(
                              ScreenUtil.getInstance().setWidth(15)),
                          child: ClipOval(
                              child: avatar == null || avatar == ""
                                  ? Image(
                                      image: AssetImage(
                                          'images/user_icon_user.png'),
                                      width: ScreenUtil.getInstance()
                                              .setWidth(750) *
                                          0.18,
                                      height: ScreenUtil.getInstance()
                                              .setWidth(750) *
                                          0.18,
                                      fit: BoxFit.cover,
                                    )
                                  : CachedNetworkImage(
                                      width: ScreenUtil.getInstance()
                                              .setWidth(750) *
                                          0.18,
                                      height: ScreenUtil.getInstance()
                                              .setWidth(750) *
                                          0.18,
                                      fit: BoxFit.cover,
                                      imageUrl: avatar.replaceAll("\\", "/"),
                                      placeholder: (context, url) =>
                                          Image.asset(
                                        'images/pic_default.png',
                                        width: ScreenUtil.getInstance()
                                                .setWidth(750) *
                                            0.18,
                                        height: ScreenUtil.getInstance()
                                                .setWidth(750) *
                                            0.18,
                                        fit: BoxFit.cover,
                                      ),
                                      errorWidget: (context, url, error) =>
                                          Image.asset(
                                        'images/pic_default.png',
                                        width: ScreenUtil.getInstance()
                                                .setWidth(750) *
                                            0.18,
                                        height: ScreenUtil.getInstance()
                                                .setWidth(750) *
                                            0.18,
                                        fit: BoxFit.cover,
                                      ),
                                    ))),
                      Expanded(
                        child: Column(
                          children: <Widget>[
                            Container(
                              alignment: Alignment.centerLeft,
                              child: Text(phone,
                                  style: TextStyle(
                                      color: Colors.black,
                                      fontSize:
                                          ScreenUtil.getInstance().setSp(30))),
                            ),
                            Container(
                              alignment: Alignment.centerLeft,
                              child: Text(nickname),
                            ),
                            Container(
                              alignment: Alignment.centerLeft,
                              child: Text(register_time),
                            ),
                          ],
                        ),
                      )
                    ],
                  )
                ],
              ),
            )),
            SliverToBoxAdapter(
                child: Container(
                    //横向滑动列表
                    color: Colors.white,
                    margin: EdgeInsets.fromLTRB(
                      0,
                      ScreenUtil.getInstance().setWidth(10),
                      0,
                      ScreenUtil.getInstance().setWidth(10),
                    ),
                    padding: EdgeInsets.fromLTRB(
                      ScreenUtil.getInstance().setWidth(10),
                      0,
                      ScreenUtil.getInstance().setWidth(10),
                      0,
                    ),
                    height: ScreenUtil.getInstance().setHeight(DP_50),
                    child: ListView.builder(
                      scrollDirection: Axis.horizontal,
                      itemCount: cates.length,
                      itemBuilder: (context, index) {
                        return zdGrid(context, index);
                      },
                    ))),
            SliverFixedExtentList(
                delegate: SliverChildBuilderDelegate(_buildListItem,
                    childCount: listData.length),
                itemExtent: ScreenUtil.getInstance().setHeight(150)),
          ]),
          onRefresh: () async {
            page = 1;
            loadList();
          },
          onLoad: () async {
            page++;
            loadList();
          }),
    );
  }

  Widget zdGrid(context, index) {
    var value = cates[index];
    return Container(
      alignment: Alignment.center,
      width: ScreenUtil.getInstance().setWidth(750) / 4,
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: groupValue == int.parse(value['cat_id'])
                ? GestureDetector(
                    child: Container(
                        // color: Colors.red,
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(width: 1, color: Colors.red))
//              border: Border.all(color: Colors.grey,width: 0.5),

//              borderRadius: BorderRadius.circular(5),
                            ),
                        alignment: Alignment.center,
                        child: Text(
                          value['cat_name'],
                          style: TextStyle(color: Colors.red,fontSize: ScreenUtil.getInstance().setSp(23)),
                        )),
                    onTap: () {
                      print('切换${value}');
                      updateGroupValue(int.parse(value['cat_id']));
                      setState(() {
                        group_id = (int.parse(value['cat_id']) + 1).toString();
                        page = 1;
                        loadList();
                      });
                    },
                  )
                : GestureDetector(
                    child: Container(
                      child: Text(value['cat_name'],
                          style: TextStyle(color: Colors.black,fontSize: ScreenUtil.getInstance().setSp(23))),
                      alignment: Alignment.center,
                    ),
                    onTap: () {
                      print('切换${value}');
                      updateGroupValue(int.parse(value['cat_id']));
                      setState(() {
                        group_id = (int.parse(value['cat_id']) + 1).toString();
                        page = 1;
                        loadList();
                      });
                    },
                  ),
            // Container(
            //   width: kMargin10,
            //   height: 1,
            // )
          )
        ],
      ),
    );
  }

  void updateGroupValue(int v) {
    setState(() {
      groupValue = v;
      print(v);
    });
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {},
        child: Container(
            color: white,
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            padding: EdgeInsets.fromLTRB(
                ScreenUtil.getInstance().setWidth(10),
                ScreenUtil.getInstance().setWidth(10),
                ScreenUtil.getInstance().setWidth(10),
                ScreenUtil.getInstance().setWidth(10)),
            child: Row(
              children: <Widget>[
                Container(
                    child: ClipOval(
                        child: listData[index]['avatar'] == null ||
                                listData[index]['avatar'] == ""
                            ? Image(
                                image: AssetImage('images/user_icon_user.png'),
                                width: ScreenUtil.getInstance().setWidth(750) *
                                    0.15,
                                height: ScreenUtil.getInstance().setWidth(750) *
                                    0.15,
                                fit: BoxFit.cover,
                              )
                            : CachedNetworkImage(
                                width: ScreenUtil.getInstance().setWidth(750) *
                                    0.15,
                                height: ScreenUtil.getInstance().setWidth(750) *
                                    0.15,
                                fit: BoxFit.cover,
                                imageUrl: listData[index]['avatar']
                                    .replaceAll("\\", "/"),
                                placeholder: (context, url) => Image.asset(
                                  'images/pic_default.png',
                                  width:
                                      ScreenUtil.getInstance().setWidth(750) *
                                          0.15,
                                  height:
                                      ScreenUtil.getInstance().setWidth(750) *
                                          0.15,
                                  fit: BoxFit.cover,
                                ),
                                errorWidget: (context, url, error) =>
                                    Image.asset(
                                  'images/pic_default.png',
                                  width:
                                      ScreenUtil.getInstance().setWidth(750) *
                                          0.15,
                                  height:
                                      ScreenUtil.getInstance().setWidth(750) *
                                          0.15,
                                  fit: BoxFit.cover,
                                ),
                              ))),
                Expanded(
                    child: Container(
                        margin: EdgeInsets.all(
                            ScreenUtil.getInstance().setWidth(15)),
                        child: Column(
                          children: <Widget>[
                            Row(children: <Widget>[
                              Expanded(
                                child:
                                    Text(listData[index]['phone'].toString()),
                              ),
                              // Expanded(
                              //     child: Container(
                              //   alignment: Alignment.centerRight,
                              //   child: Text(listData[index]['action_symbol'].toString() +
                              //       '¥' +
                              //       listData[index]['money'].toString()),
                              // ))
                            ], crossAxisAlignment: CrossAxisAlignment.start),
                            Container(
                              height: 10,
                            ),
                            Row(children: <Widget>[
                              Expanded(
                                child: Text(
                                  '购买时间:' +
                                      listData[index]['register_time']
                                          .toString(),
                                  style: TextStyle(
                                      fontSize:
                                          ScreenUtil.getInstance().setSp(24)),
                                ),
                              ),
                              //   Expanded(
                              //       child: Container(
                              //     alignment: Alignment.centerRight,
                              //     child: Text(
                              //         '当前总额:¥' + listData[index]['all_money'].toString()),
                              //   ))
                            ], crossAxisAlignment: CrossAxisAlignment.start),
                            // Divider(
                            //   height: 1,
                            // )
                          ],
                        )))
              ],
            )));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      data();
      loadList();
    });
  }

  data() async {
    FormData data = new FormData.fromMap({'token': token});
    Response<String> response =
        await HttpUtil().post(Api.GetTeamListStatistics, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    int code = userMap["code"];
    String msg = userMap["msg"];
    if (code == 1 && mounted) {
      setState(() {
        phone = userMap['data']['referrerMsg']['phone'];
        nickname = userMap['data']['referrerMsg']['nickname'];
        register_time = userMap['data']['referrerMsg']['register_time'];
        avatar = userMap['data']['referrerMsg']['avatar'];
        cates = [
          {
            'cat_id': '0',
            'cat_name': '普通会员(' + userMap['data']['user_num'].toString() + ')'
          },
          {
            'cat_id': '1',
            'cat_name': '产品礼包1(' + (int.parse(userMap['data']['vip1_num2'].toString())+int.parse(userMap['data']['vip1_num1'].toString())).toString() + ')'
          },
          {
            'cat_id': '2',
            'cat_name': '产品礼包2(' + userMap['data']['vip2_num'].toString() + ')'
          },
          {
            'cat_id': '3',
            'cat_name': '产品礼包3(' + userMap['data']['vip3_num'].toString() + ')'
          }
        ];
      });
    }
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['p'] = page.toString();
    map['group_id'] = group_id;
    print(map);
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.GetTeamListUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    int code = userMap["code"];
    String msg = userMap["msg"];
    if (code == 1 && mounted) {
      setState(() {
        if (page == 1) {
          listData.clear();
          listData = userMap['data']['teamlist'];
          _controller.finishRefresh();
        } else {
          listData.addAll(userMap['data']['teamlist']);
          _controller.finishLoad();
        }
      });
    }
  }
}
